package net.topicopedia.servlets.topics;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class GetUserTopicServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String userTopicId = req.getParameter("topic");
		Key userTopicKey = KeyFactory.createKey("UserTopic",  (Long) Long.parseLong(userTopicId));
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Entity userTopic;
		try {
			userTopic = datastore.get(userTopicKey);
			String storedUuid = userTopic.getKey().getId() + "";
			String userUuid = ( (Key) userTopic.getProperty("user") ).getId() + "";
			String topicUuid = ( (Key) userTopic.getProperty("topic") ).getId() + "";
			String items = ( ( Text) userTopic.getProperty("items") ).getValue();
			String references = ( ( Text) userTopic.getProperty("references") ).getValue();
			
			Key topicKey = KeyFactory.createKey("Topic", topicUuid);
			
			Entity topic = datastore.get(topicKey);
			
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setContentType("text/plain");
			
			String output = "{\"uuid\": " + storedUuid;
			output += ", \"user\": " + userUuid;
			output += ", \"topic\": " + topicUuid;
			if ( items.length() > 0 )
			{
				output += ", \"items\": " + items;
			}
			if ( references.length() > 0 )
			{
				output += ", \"references\": " + references;
			}
			output += "}";
			 
			resp.getWriter().println( output );
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
		}

		
		
	}
}
 